import math
from datetime import datetime


calculation_history = []


def show_menu():
    """显示主菜单"""
    print("\n" + "=" * 40)
    print("多功能科学计算器".center(40))
    print("=" * 40)
    print("1. 基础运算（加减乘除模）")
    print("2. 科学计算（指数/对数/三角函数）")
    print("3. 单位转换")
    print("4. 查看历史记录")
    print("5. 清空历史记录")
    print("0. 退出程序")
    print("=" * 40)


def basic_calculation():
    """基础四则运算"""
    print("\n【基础运算模式】")
    try:
        num1 = float(input("输入第一个数字: "))
        operator = input("选择运算 (+ - * / %): ")
        num2 = float(input("输入第二个数字: "))

        result = None
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '*':
            result = num1 * num2
        elif operator == '/':
            if num2 == 0:
                raise ZeroDivisionError
            result = num1 / num2
        elif operator == '%':
            result = num1 % num2
        else:
            print("无效运算符！")
            return

        record = f"{num1} {operator} {num2} = {result}"
        calculation_history.append(record)
        print(f"计算结果: {result}")

    except ValueError:
        print("错误：请输入有效数字！")
    except ZeroDivisionError:
        print("错误：除数不能为零！")


def scientific_calculation():
    """科学计算功能"""
    print("\n【科学计算模式】")
    print("a. 平方根  b. 平方  c. 立方")
    print("d. 阶乘    e. 指数  f. 对数")
    print("g. sin    h. cos   i. tan")

    choice = input("请选择计算类型: ").lower()

    try:
        if choice in ['a', 'b', 'c', 'g', 'h', 'i']:
            num = float(input("输入数字: "))
            if choice == 'a':
                if num < 0:
                    raise ValueError
                result = math.sqrt(num)
                record = f"√{num} = {result}"
            elif choice == 'b':
                result = num ** 2
                record = f"{num}² = {result}"
            elif choice == 'c':
                result = num ** 3
                record = f"{num}³ = {result}"
            elif choice == 'g':
                result = math.sin(math.radians(num))
                record = f"sin({num}°) = {result}"
            elif choice == 'h':
                result = math.cos(math.radians(num))
                record = f"cos({num}°) = {result}"
            elif choice == 'i':
                result = math.tan(math.radians(num))
                record = f"tan({num}°) = {result}"

        elif choice == 'd':
            num = int(input("输入整数: "))
            if num < 0:
                raise ValueError
            result = math.factorial(num)
            record = f"{num}! = {result}"

        elif choice == 'e':
            base = float(input("输入底数: "))
            exp = float(input("输入指数: "))
            result = base ** exp
            record = f"{base}^{exp} = {result}"

        elif choice == 'f':
            num = float(input("输入真数: "))
            base = float(input("输入底数: "))
            if num <= 0 or base <= 0 or base == 1:
                raise ValueError
            result = math.log(num, base)
            record = f"log_{base}({num}) = {result}"

        else:
            print("无效选择！")
            return

        calculation_history.append(record)
        print(f"计算结果: {result}")

    except ValueError as ve:
        print("错误：输入值不符合要求！")


def unit_converter():
    """单位转换工具"""
    print("\n【单位转换模式】")
    print("1. 温度转换（℃↔℉）")
    print("2. 长度转换（米↔英尺）")
    print("3. 重量转换（公斤↔磅）")

    choice = input("请选择转换类型: ")

    try:
        value = float(input("输入需要转换的数值: "))

        if choice == '1':
            direction = input("转换方向（1.℃→℉  2.℉→℃）: ")
            if direction == '1':
                result = value * 9 / 5 + 32
                record = f"{value}℃ = {result}℉"
            else:
                result = (value - 32) * 5 / 9
                record = f"{value}℉ = {result}℃"

        elif choice == '2':
            direction = input("转换方向（1.米→英尺  2.英尺→米）: ")
            if direction == '1':
                result = value * 3.28084
                record = f"{value}米 = {result}英尺"
            else:
                result = value / 3.28084
                record = f"{value}英尺 = {result}米"

        elif choice == '3':
            direction = input("转换方向（1.公斤→磅  2.磅→公斤）: ")
            if direction == '1':
                result = value * 2.20462
                record = f"{value}公斤 = {result}磅"
            else:
                result = value / 2.20462
                record = f"{value}磅 = {result}公斤"

        else:
            print("无效选择！")
            return

        calculation_history.append(record)
        print(f"转换结果: {record}")

    except ValueError:
        print("错误：请输入有效数字！")


def show_history():
    """显示计算历史"""
    print("\n【计算历史记录】")
    if not calculation_history:
        print("暂无历史记录")
        return

    for index, record in enumerate(calculation_history, 1):
        print(f"{index}. {record}")

    print(f"\n总计 {len(calculation_history)} 条记录")


def main():
    print("欢迎使用多功能计算器！")
    while True:
        show_menu()
        choice = input("请输入选项: ")
        if choice == '0':
            print("感谢使用，再见！")
            break
        elif choice == '1':
            basic_calculation()
        elif choice == '2':
            scientific_calculation()
        elif choice == '3':
            unit_converter()
        elif choice == '4':
            show_history()
        elif choice == '5':
            calculation_history.clear()
            print("历史记录已清空！")
        else:
            print("无效输入，请重新选择！")
        input("\n按回车键继续...")


if __name__ == "__main__":
    main()